package dao.impl;

import dao.IUserDao;
import entity.Goods;

public class DaoImpl implements IUserDao{
	private Goods[] goods;
	Goods[] un = new Goods[20];
	int u = 0;
	public DaoImpl(){
		goods = new Goods[20];
	}
	private int getUsefulIndex(){
		for (int i = 0; i < goods.length; i++) {
			if(null == goods[i]){
				return i;
			}
		}
		return -1;
	}
	@Override
	public boolean save(Goods good) {
		int index = this.getUsefulIndex();
		if(-1 == index){
			return false;
		}
		goods[index] = good;
		return true;
	}
	@Override
	public boolean delete(Goods good) {
		int index = getUsefulIndex();
		for (int i = 0; i < index; i++) {
			if(goods[i].getId()==good.getId()){
				for (int j = i; j < index-1; j++) {
					goods[j] = goods[j+1];
				}
				un[u++] = goods[i];
				goods[i].selling = true;
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean updateById(Goods goods) {
		for (int i = 0; i < this.goods.length && this.goods[i]!=null; i++) {
			if(this.goods[i].getId() == goods.getId()){
				this.goods[i] = goods;
				return true;
			};
		}
		return false;
	}

	@Override
	public Goods[] selectAll() {
		return goods;
	}

	@Override
	public Goods selectById(int id) {
		for (int i = 0; i < goods.length && goods[i]!=null; i++) {
			if(goods[i].getId() == id);
			return goods[i];
		}
		return null;
	}
	//----------------------ssw--------------------
	@Override
	public Goods[] selectByName(String name) {
		Goods[] news = new Goods[20];
		for (int i = 0,j = 0; i < goods.length && goods[i]!=null; i++) {
			if(goods[i].getName().equals(name)){
				news[j++] = goods[i];
			}
		}
		return news;
	}

	@Override
	public Goods[] selectByPrice(int low, int high) {
		Goods[] copy = new Goods[20];
		System.arraycopy(goods, 0, copy, 0, goods.length);
		
		for (int i = 0; i < copy.length-1 && copy[i]!=null; i++) {
			for (int j = 0; j < copy.length -1 -i && copy[j+1]!=null; j++) {
				if(copy[j].getPrice()> copy[j+1].getPrice()){
					Goods temp = copy[j];
					copy[j] = copy[j+1];
					copy[j+1] = temp;
				}
			}
		}
		return copy;
	}

	
	//---------------------zj-------------------
	@Override
	public Goods[] selectAllUnselling() {
		// TODO Auto-generated method stub
		return un;
	}

	@Override
	public Goods[] sortByNum() {
		Goods[] copy = new Goods[20];
		System.arraycopy(goods, 0, copy, 0, goods.length);
		for (int i = 0; i < copy.length-1 && copy[i] != null; i++) {
			for (int j = 0; j < copy.length-1-i && copy[j] != null; j++) {
				if(copy[j].getNum() > copy[j+1].getNum()){
					Goods temp = copy[j];
					copy[j] = copy[j+1];
					copy[j+1] = temp;
				}
			}
		}
		return copy;
	}
	
	
}
